<template>
	<uni-forms class="login-form" :model="formData" :rules="formRules" ref="form">
		<uni-forms-item name="mobile">
			<uni-easyinput
				:input-border="false"
				:clearable="false"
				v-model="formData.mobile"
				placeholder="请输入手机号"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<uni-forms-item name="code">
			<uni-easyinput
				:input-border="false"
				:clearable="false"
				v-model="formData.code"
				placeholder="请输入验证码"
				placeholder-style="color: #C3C3C5"
			/>
			<custom-countdown
				v-if="!hasCode"
				@timeup="codeTimeUp"
				color="#16C2A3"
				:showDay="false"
				:showHour="false"
				:showMinute="false"
				:second="5"
			></custom-countdown>
			<text class="text-button" @click="changeCode">{{
				hasCode ? '获取验证码' : '后再次获取验证码'
			}}</text>
		</uni-forms-item>

		<view class="agreement">
			<radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
			我已同意
			<text class="link">用户协议</text>
			及
			<text class="link">隐私协议</text>
		</view>

		<button class="uni-button" @click="getLogin">登 录</button>
	</uni-forms>
</template>
<script setup>
	import { ref } from 'vue'
	import { reqGetCode, reqGetLogin } from '../../../services/user'
	import { useUserStore } from '../../../stores/user'
	let hasCode = ref(true)
	let codeText = ref('获取验证码')
	let form = ref()
	let formData = ref({
		mobile: '',
		code: '',
	})
	let isAgree = ref(false)
	// 验证表单数据的规则
	const formRules = {
		mobile: {
			rules: [
				{ required: true, errorMessage: '请填写手机号码' },
				{ pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
			],
		},
		code: {
			rules: [
				{ required: true, errorMessage: '请输入验证码' },
				{ pattern: '^\\d{6}$', errorMessage: '验证码格式不正确' },
			],
		},
	}
	const userStore = useUserStore()
	const getLogin = async () => {
		if (!isAgree.value) return uni.utils.toast('请勾选协议')
		try {
			let res = await form.value.validate()
			let { data, code, message } = await reqGetLogin(res)
			if (code !== 10000) return uni.utils.toast(message)
			userStore.token = data.token
			uni[userStore.openType]({ url: `${userStore.redirectUrl}` })
		} catch (e) {
			//TODO handle the exception
			console.log(e)
		}
	}
	const changeCode = async () => {
		let { data, code, message } = await reqGetCode({
			mobile: formData.value.mobile,
			type: 'login',
		})
		console.log(data)
		if (code !== 10000) return uni.utils.toast(message)
		hasCode.value = !hasCode.value
	}
	const codeTimeUp = () => {
		hasCode.value = !hasCode.value
	}
</script>
<script>
	export default {
		name: 'Mobile',
		options: {
			styleIsolation: 'shared',
		},
	}
</script>

<style lang="scss">
	@import './style.scss';
</style>
